<?php
/*****************************
* PHPwork官方网址： ruanjiesoft.com
* PHPwork应用官方QQ群： 317075601
* PHPwork应用开发者QQ： 1980572700
* 不得使用本软件用于非法用途，不得违反国家法律。
*************************************/

namespace system\api\controller;

use function GuzzleHttp\json_decode;
use EasyWeChat\Factory;

// 微信公众号
class WeChat{

	private $app;

	function __construct(){

		$this->app = $GLOBALS['wechat']['app'];

	}

	// 服务器验证 与 消息的接收与回复 接口配置信息的 url 
	function index(){   

		// 首次关注
		//$this->app->server->push(function ($message) {
		//    return "您好！欢迎使用 EasyWeChat! - phpwork api";
		//});

		$response = $this->app->server->serve();

		// 将响应输出
		$response->send();exit; // Laravel 里请使用：return $response;

	} 


    // 网页授权 oauth
	function oauth(){

        $user = $this->app->oauth->user();

        $_SESSION['wechat_user'] = $user->toArray();

        $targetUrl = empty($_SESSION['target_url']) ? '/' : $_SESSION['target_url'];
        //header('location:'. url( [ 'demo_wechat' ,'index','oauth','index.php'] )); // 跳转到 user/profile
        header('location:'. $targetUrl); // 跳转到 user/profile
		exit;
    }

	// 统一下单接口
	// index.php?s=api/wechat/prepay
    function prepay(){
		
		wechat_oauth_userinfo();
		
		$order_sn = $_REQUEST['order_sn'];
		$total_fee = floatval($_REQUEST['fee']) * 100;		// 元转分
		$body = isset($_REQUEST['body'])?$_REQUEST['body'] : '商品简单描述';
        $attach = [ 'module' => $_REQUEST['module'] ];
		$attach['data'] = isset($_REQUEST['attach'])?$_REQUEST['attach'] : '';	//附件数据
        $attach = json_encode($attach);

        $config = [ // 必要配置
            'app_id'             => $GLOBALS['wechat']['config']['appid'],	// 
            'mch_id'             => $GLOBALS['wechat']['config']['mch_id'],	//
            'key'                => $GLOBALS['wechat']['config']['apikey'],	// API 密钥        
            'notify_url'         => $GLOBALS['wechat']['config']['notify_url'],     // 支付成功后回调地址
        ];

        
        $app = Factory::payment($config);

        $result = $app->order->unify([
            'body' => $body,
            'out_trade_no' => $order_sn,  // 订单号唯一
            'total_fee' => $total_fee ,			// 单位,分
            //'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $GLOBALS['wechat']['member']['openid'] ,
            'attach' => $attach ,
        ]);

        $jssdk = $app->jssdk;
        $json = $jssdk->bridgeConfig($result['prepay_id']);

        echo $json;	// 微信内H5调起支付 参数

    }
	
	// 支付回调
	// index.php?s=api/wechat/notify
    function notify(){

//$xml_data = <<<EOF
//<xml><appid><![CDATA[wx8908532a27c5dd4f]]></appid>
//<attach><![CDATA[{"module":"demo_wechat"}]]></attach>
//<bank_type><![CDATA[CFT]]></bank_type>
//<cash_fee><![CDATA[1]]></cash_fee>
//<fee_type><![CDATA[CNY]]></fee_type>
//<is_subscribe><![CDATA[N]]></is_subscribe>
//<mch_id><![CDATA[1509822581]]></mch_id>
//<nonce_str><![CDATA[ca1fe6d2b4f667cf249bd1d7176c6178]]></nonce_str>
//<openid><![CDATA[oZDDE5JLnVyc6qe6nbNWdbFHtY5I]]></openid>
//<out_trade_no><![CDATA[2019040155491005]]></out_trade_no>
//<result_code><![CDATA[SUCCESS]]></result_code>
//<return_code><![CDATA[SUCCESS]]></return_code>
//<sign><![CDATA[3880232710B7328822D079DC405FB09D]]></sign>
//<time_end><![CDATA[20190401104804]]></time_end>
//<total_fee>1</total_fee>
//<trade_type><![CDATA[JSAPI]]></trade_type>
//<transaction_id><![CDATA[4200000265201904014227830207]]></transaction_id>
//</xml>
//EOF;

		if (!$xml_data = file_get_contents('php://input')) {
			echo $this->return_xml( 'FAIL', 'Not found DATA' );
			return;
		}
		// 将服务器返回的XML数据转化为数组
		libxml_disable_entity_loader(true);
		$xml = json_decode(json_encode(simplexml_load_string($xml_data, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		$attach=json_decode( $xml['attach'] ,true);

		$data = [
			'module' => $attach['module'],					//模块标识
			'trade_type' => $xml['trade_type'],				// 交易类型(JSAPI、NATIVE、APP)
			'mch_id' => $xml['mch_id'],
			'openid' => $xml['openid'],
			'out_trade_no' => $xml['out_trade_no'],			//商户订单号
			'transaction_id' => $xml['transaction_id'],		//微信支付订单号
			'total_fee' => $xml['total_fee'],				//订单总金额，单位为分
			'cash_fee' => $xml['cash_fee'],					//现金支付金额，单位为分
			'result_code' => $xml['result_code'],		//业务结果(SUCCESS,FAIL)
			'time_end' => $xml['time_end'],				//支付完成时间

			'notify_data' => $xml_data ,					//回调数据流
			'create_time' => date('Y-m-d H:i:s'),
		  ];
		$ok = pdo_insert('sys_wechat_pay_log',$data);
	  
		if($ok){
			try{

				$app = $attach['module'] ;

				if( file_exists( _APP_PATH_ . "/application/{$app}/notify.class.php" ) ){
					require _APP_PATH_ . "/application/{$app}/notify.class.php";
					$class= 'application\\'.$app.'\\Notify' ;
					$o = new $class();
					$o->wechat($xml);
				}else{
					echo $this->return_xml( 'FAIL', 'PHPwork notify.class.php no file' );
					exit;	
				}




			}catch(\Throwable $e){
				echo $this->return_xml( 'FAIL', 'PHPwork notify.class.php exception' );
				exit;
			}			

		}else{
			echo $this->return_xml( 'FAIL', 'PHPwork sys_wechat_order error' );
			exit;
		}

		//
		echo $this->return_xml( 'SUCCESS', 'OK' );
		exit;

	}

	private function return_xml($code='',$msg=''){
		$xml='';
		$xml.='<xml>';
		$xml.="<return_code><![CDATA[$code]]></return_code>";
		$xml.="<return_msg><![CDATA[$msg]]></return_msg>";
		$xml.='</xml>';
		return $xml;
	}

  
}